package org.gaaidou.ptarmigan.springboot.data.jpa.datasource;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Order(2)
@Component
@Slf4j
public class RoutingDataSourceAop {


    @Around("@annotation(org.gaaidou.ptarmigan.springboot.data.jpa.datasource.DataSourceRouter)")
    public Object dataSourceRouter(ProceedingJoinPoint point) throws Throwable {
        Method method = ((MethodSignature) point.getSignature()).getMethod();
        try {
            RouteStrategyHolder.use(method.getAnnotation(DataSourceRouter.class).value());
            return point.proceed();
        } finally {
            RouteStrategyHolder.clear();
        }
    }

}
